package com.tinem.platform.service.network.client.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.module.starter.jpa.entity.network.IpInfo;
import com.tinem.platform.service.network.client.IpInfoClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className TengXun
 * @description 通过腾讯获取ip信息
 * @site
 * @company
 * @create 2021-10-27 14:38
 */
@Slf4j
@Service
public class TengXunIpInfoClient  implements IpInfoClient {

    String source = "market";

    //云市场分配的密钥Id
    @Value("${tengxun.secret-id}")
    String secretId;
    //云市场分配的密钥Key
    @Value("${tengxun.secret-key}")
    String secretKey;
    @Value("${tengxun.url}")
    String url;

    @Override
    public IpInfo getLocationByIp(String ip) {
        log.info("api tengxin ip:{}",ip);
        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String datetime = sdf.format(cd.getTime());
        // 签名
        String auth = null;
        try {
            auth = calcAuthorization(datetime);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e ) {
            log.info("api tengxin ip error",e);
            return null;
        }
        String url = StrUtil.format(this.url,ip);
        HttpRequest request = HttpRequest.get(url);
        request.header("X-Source", source);
        request.header("X-Date", datetime);
        request.header("Authorization", auth);
        log.info("api tengxin url:{} X-Source:{}  X-Date:{} Authorization:{}",url,source,datetime,auth);
        String result = request.execute().body();
        log.info("api tengxin res:{}",result);
        JSONObject jsonObject = JSON.parseObject(result);
        JSONObject region = jsonObject.getJSONObject("data");
        JSONObject details = region.getJSONObject("details");
        IpInfo ipInfo = new IpInfo();
        ipInfo.setIp(ip);
        ipInfo.setCountry(region.getString("country"));
        if(details != null){
            ipInfo.setRegion(details.getString("region"));
            ipInfo.setCity(details.getString("city"));
        }
        return ipInfo;
    }

    public String calcAuthorization(String datetime)
            throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
        Mac mac = Mac.getInstance("HmacSHA1");
        Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
        mac.init(sKey);
        byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
        String sig = Base64.encode(hash);

        String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
        return auth;
    }
}
